package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service

public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private ArticleFeign articleFeign;

    /**
     * 用户关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //校验参数
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "作者信息不能为空");
        }

        //2.获取作者
        ApAuthor apAuthor = articleFeign.findByUserId(dto.getAuthorId());
        //文章作者的id
        Integer followId = null;
        if (apAuthor != null) {
            followId = apAuthor.getUserId();
        }
        if (followId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注人不存在");
        } else {
            ApUser apUser = AppThreadLocalUtils.getUser();
            if (apUser != null) {
                if (dto.getOperation() == 0) {
                    //关注作者
                    //3.如果当前操作是0 创建数据（app用户关注信息和app的用户粉丝信息）
                    return followByUserId(apUser, followId, dto.getArticleId());
                } else {
                    //取消关注
                    //4.如果当前操作是1 删除数据（app用户关注信息和app的用户粉丝信息）
                    return followCancelByUserId(apUser, followId);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
        }
    }

    //取消关注作者
    private ResponseResult followCancelByUserId(ApUser apUser, Integer followId) {
        //先查再删
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未关注!!");
        } else {
            //查询粉丝表用户是否存在
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followId)
                    .eq(ApUserFan::getFansId, apUser.getId()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未关注");
            } else {
                //删除粉丝表
                apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getUserId, followId)
                        .eq(ApUserFan::getFansId, apUser.getId()));
            }
            //删除关注表
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, apUser.getId())
                    .eq(ApUserFollow::getFollowId, followId));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    //关注作者
    private ResponseResult followByUserId(ApUser apUser, Integer followId, Long articleId) {
        //判断当前作者是否存在
        ApUser followUser = apUserMapper.selectById(followId);
        if (followUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注用户不存在!");
        }
        //先查看是否已经关注该用户
        LambdaQueryWrapper<ApUserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUserFollow::getUserId, apUser.getId());
        wrapper.eq(ApUserFollow::getFollowId, followId);
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(wrapper);
        if (apUserFollow == null) {
            //说明没有关注该作者,可以关注作者
            //保存关注表
            apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(apUser.getId());
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setFollowId(followId);
            apUserFollow.setIsNotice(true);
            apUserFollow.setLevel((short) 1);
            apUserFollowMapper.insert(apUserFollow);
            //判断作者粉丝表是否保存
            LambdaQueryWrapper<ApUserFan> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(ApUserFan::getFansId, apUser.getId());
            wrapper1.eq(ApUserFan::getUserId, followId);
            ApUserFan apUserFan = apUserFanMapper.selectOne(wrapper1);

            if (apUserFan == null) {
                //保存粉丝表
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(apUser.getId().longValue());
                apUserFan.setFansName(followUser.getName());
                apUserFan.setLevel((short) 0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanMapper.insert(apUserFan);
                //记录关注行为
                FollowBehaviorDto dto = new FollowBehaviorDto();
                dto.setUserId(AppThreadLocalUtils.getUser().getId());
                dto.setArticleId(articleId);
                dto.setFollowId(followId);
                //发送异步消息,保存关注行为
                kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            //已关注
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已关注");
        }
    }
}
